package com.paul.web.security;

import com.paul.common.constant.RedisKeyConst;
import com.paul.common.exception.BusinessException;
import com.paul.common.exception.ExceptionCode;
import com.paul.common.utils.*;
import com.paul.redis.utils.RedisUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * @author ZMK
 * @date 2022/12/19 13:34
 * @description
 */
@Component
public class SignFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(SignFilter.class);
    private String[] WhiteList = {"0:0:0:0:0:0:0:1"};

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //内部调用直接跳过签名，根据域名或者IP区分
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        String ipAddr = IpUtil.getIpAddr(httpServletRequest);
        String reqURI = httpServletRequest.getRequestURI();

        if (ArrayUtils.contains(WhiteList, ipAddr) || reqURI.contains("-internal")) {
            chain.doFilter(httpServletRequest, response);
            return;
        }
        String timeStamp = httpServletRequest.getHeader("timeStamp");
        String nonceStr = httpServletRequest.getHeader("nonceStr");
        if (StringUtils.isBlank(timeStamp) || StringUtils.isBlank(nonceStr)) {
            httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "签名参数错误");
            return;
        }

        //判断有效期 5分钟
        if (!DateUtil.isMinutesDiff(DateUtil.strToDateTime(timeStamp), PaulUtil.getNowDate(), 5)) {
            httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "签名已过期");
            return;
        }
        //判断是否重复访问 MD5(ipAddr+nonceStr) 60s内
        String key = MD5Util.getMD5(ipAddr + nonceStr);
        String reqKey = RedisKeyConst.REQUEST_ID + key;
        if (redisUtil.increment(reqKey, 1) > 1) {
            throw new BusinessException(ExceptionCode.REPEATED_REQUESTS.value(), "请求太频繁,请稍后再试！");
        }
        redisUtil.expire(reqKey, 60);

        if (!PaulSignUtil.verify(httpServletRequest)) {
            httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "签名失败");
            return;
        }
        chain.doFilter(httpServletRequest, response);
    }

    @Override
    public void destroy() {

    }
}
